#include <iostream>
#include "stdTcpServer.h"
#include "threadpool.h"
#include <pthread.h>
#include <json-c/json.h>
#include "stdShared.h"
#include "messageHandle.h"

#define SERVER_PORT 8888
#define BUFFER_SIZE 128
using namespace std;

void* handleClientInfo(void *arg)
{
    /* 线程分离 */
    // pthread_detach(pthread_self());

    StdTcpSocketPtr clientInfo = *static_cast<StdTcpSocketPtr *>(arg);

    MessageHandle handler(clientInfo);

    int readBytes = 0;
    string buffer;
    while(1)
    {
        readBytes =  clientInfo->recvMessage(buffer);
        if(readBytes < 0)
        {
            perror("readBytes < 0");
            break;
        }
        else if(readBytes == 0)
        {
            std::cout << "客户端下线!" << std::endl;
            break;
        }
        else
        {
            handler.handleMessage(buffer);
        }

        /* 情况缓冲区 */
        buffer.clear();
        //clientInfo->sendMessage(buffer, sizeof(buffer));
    }
    /* 资源回收 */
    close(clientInfo->getSockAttr()->connfd);

    return NULL;
}


int main()
{
    /* 启动线程池 */
    ThreadPool pool(2, 5, 20);

    StdTcpServer server;

    /* 启动监听 */
    server.setListen(SERVER_PORT);
    cout << "等待客户端接收..."  << endl;

    while(1)
    {
        /* 阻塞客户端连接 */
        StdTcpSocketPtr clientInfo =  server.getClientSock();
#if 0
        /* 给客户端创建独立的线程 */
        pthread_t tid;
        int ret = pthread_create(&tid, NULL, handleClientInfo, &clientInfo);
        if(ret != 0)
        {
            perror("thread create error:");
            continue;
        }
        
#else
        /* 放到任务队列 */
        pool.addTask(handleClientInfo, new StdTcpSocketPtr(clientInfo));
#endif
        sleep(1);
    }


    return 0;
}